package com.yuancheng.modules.msweb.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yuancheng.common.api.vo.Result;
import com.yuancheng.common.constant.CommonConstant;
import com.yuancheng.common.system.query.QueryGenerator;
import com.yuancheng.common.util.DateUtils;
import com.yuancheng.common.util.oConvertUtils;
import com.yuancheng.modules.msweb.entity.Btable;
import com.yuancheng.modules.msweb.entity.DeviceInfo;
import com.yuancheng.modules.msweb.entity.EventDic;
import com.yuancheng.modules.msweb.service.IDeviceInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuancheng.modules.online.cgreport.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 设备
 * @author： yuancheng
 * @date： 2020-01-08
 * @version： V1.0
 */
@RestController
@RequestMapping("/msweb/deviceInfo")
@Slf4j
public class DeviceInfoController {
    @Autowired
    private IDeviceInfoService deviceInfoService;

    /**
     * 分页列表查询
     *
     * @param deviceInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<DeviceInfo>> queryPageList(DeviceInfo deviceInfo,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        Result<IPage<DeviceInfo>> result = new Result<IPage<DeviceInfo>>();

        String devnum = deviceInfo.getDevnum();
        deviceInfo.setDevnum(null);
        String devname = deviceInfo.getDevname();
        deviceInfo.setDevname(null);

        QueryWrapper<DeviceInfo> queryWrapper = QueryGenerator.initQueryWrapper(deviceInfo, req.getParameterMap());
        Page<DeviceInfo> page = new Page<DeviceInfo>(pageNo, pageSize);
        if (oConvertUtils.isNotEmpty(devnum)) {
            queryWrapper.like("devnum", devnum);
        }
        if (oConvertUtils.isNotEmpty(devname)) {
            queryWrapper.like("devname", devname);
        }
        IPage<DeviceInfo> pageList = deviceInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param deviceInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/listByDevnums")
    public Result<IPage<DeviceInfo>> listByDevnums(DeviceInfo deviceInfo,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   @RequestParam(name = "devnums") String devnums,
                                                   HttpServletRequest req) {
        Result<IPage<DeviceInfo>> result = new Result<IPage<DeviceInfo>>();
        QueryWrapper<DeviceInfo> queryWrapper = QueryGenerator.initQueryWrapper(deviceInfo, req.getParameterMap());

        String[] devnumList = {};
        if (!StringUtil.isEmpty(devnums)) {
            devnumList = devnums.split(",");
        }
        queryWrapper.in("devnum", devnumList);
        Page<DeviceInfo> page = new Page<DeviceInfo>(pageNo, pageSize);
        IPage<DeviceInfo> pageList = deviceInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 校验设备编号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param tcRechargeDiscount
     * @return
     */
    @RequestMapping(value = "/checkOnlyDevnum", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyDevnum(DeviceInfo tcRechargeDiscount) {
        Result<Boolean> result = new Result<>();
        result.setResult(true);//如果此参数为false则程序发生异常
        Integer id = tcRechargeDiscount.getId();
        log.info("--验证事件信息是否唯一---id:" + id);
        try {
            DeviceInfo oldRechargeDiscount = null;
            if (oConvertUtils.isNotEmpty(id)) {
                oldRechargeDiscount = deviceInfoService.getById(id);
                tcRechargeDiscount.setId(null);
            }
            //通过传入信息查询新的用户信息
            DeviceInfo newRechargeDiscount = deviceInfoService.getOne(new QueryWrapper<DeviceInfo>(tcRechargeDiscount));
            if (newRechargeDiscount != null) {
                //如果根据传入信息查询到用户了，那么就需要做校验了。
                if (oldRechargeDiscount == null) {
                    //oldUser为空=>新增模式=>只要用户信息存在则返回false
                    result.setSuccess(false);
                    result.setMessage("设备编号已存在!");
                    return result;
                } else if (!id.equals(newRechargeDiscount.getId())) {
                    //否则=>编辑模式=>判断两者ID是否一致-
                    result.setSuccess(false);
                    result.setMessage("设备编号已存在!");
                    return result;
                }
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setResult(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 添加
     *
     * @param deviceInfo
     * @return
     */
    @PostMapping(value = "/add")
    public Result<DeviceInfo> add(@RequestBody DeviceInfo deviceInfo) {
        Result<DeviceInfo> result = new Result<DeviceInfo>();
        try {
            deviceInfo.setAddTime(DateUtils.formatDateTime());
            deviceInfoService.save(deviceInfo);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param deviceInfo
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<DeviceInfo> edit(@RequestBody DeviceInfo deviceInfo) {
        Result<DeviceInfo> result = new Result<DeviceInfo>();
        DeviceInfo deviceInfoEntity = deviceInfoService.getById(deviceInfo.getId());
        if (deviceInfoEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = deviceInfoService.updateById(deviceInfo);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<DeviceInfo> delete(@RequestParam(name = "id", required = true) String id) {
        Result<DeviceInfo> result = new Result<DeviceInfo>();
        DeviceInfo deviceInfo = deviceInfoService.getById(id);
        if (deviceInfo == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = deviceInfoService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<DeviceInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<DeviceInfo> result = new Result<DeviceInfo>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.deviceInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<DeviceInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<DeviceInfo> result = new Result<DeviceInfo>();
        DeviceInfo deviceInfo = deviceInfoService.getById(id);
        if (deviceInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(deviceInfo);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public HttpServletResponse exportXls(HttpServletRequest request, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            String path = CommonConstant.TEMP_URL + "设备列表.xls";
            File file = new File(path);

            //设置发送到客户端的响应的内容类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");

            // 取得文件名。
            String filename = file.getName();
            filename = URLEncoder.encode(filename, "UTF-8");
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                Integer saveSize = 0;
                Integer updateSize = 0;
                List<DeviceInfo> listDeviceInfos = ExcelImportUtil.importExcel(file.getInputStream(), DeviceInfo.class, params);
                for (DeviceInfo deviceInfoExcel : listDeviceInfos) {
                    String devnum = deviceInfoExcel.getDevnum();
                    String devname = deviceInfoExcel.getDevname();
                    if (StringUtil.isEmpty(devnum) || StringUtil.isEmpty(devname)) {
                        continue;
                    }
                    QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("devnum", devnum);
                    List<DeviceInfo> list = deviceInfoService.list(queryWrapper);
                    if (list != null && list.size() != 0) {
                        deviceInfoExcel.setId(list.get(0).getId());
                        deviceInfoService.updateById(deviceInfoExcel);
                        updateSize++;
                        continue;
                    }
                    deviceInfoExcel.setAddTime(DateUtils.formatDateTime());
                    deviceInfoService.save(deviceInfoExcel);
                    saveSize++;
                }
                return Result.ok("文件导入成功！新增:" + saveSize+",修改:"+updateSize);
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
